package com.ckh.springboot.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ckh.springboot.common.Constants;
import com.ckh.springboot.common.Result;
import com.ckh.springboot.entity.JoinClass;
import com.ckh.springboot.entity.SysClass;
import com.ckh.springboot.entity.User;
import com.ckh.springboot.service.IJoinClassService;
import com.ckh.springboot.service.ISysClassService;
import com.ckh.springboot.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ckh
 * @since 2022-04-04
 */
@RestController
@RequestMapping("/api/joinClass")
public class JoinClassController {

    @Resource
    private IJoinClassService joinClassService;

    @Resource
    private ISysClassService sysClassService;

    @Resource
    private IUserService userService;


    /**
     * 加入班级
     * @return
     */
    @GetMapping("/joinClassInsert")
    public Result save(@RequestParam String key,@RequestParam Integer userId) {
        //根据key查看班级是否存在
        SysClass one = sysClassService.getOne(Wrappers.<SysClass>lambdaQuery().eq(SysClass::getClassKey, key));
        if(ObjectUtils.isEmpty(one)){
                return Result.error(Constants.CODE_400, "班级不存在!");
        }

        //判断是否加入过本班级
        JoinClass one1 = joinClassService.getOne(Wrappers.<JoinClass>lambdaQuery().eq(JoinClass::getClassId, one.getId())
                .eq(JoinClass::getUserId, userId));
        if(ObjectUtils.isNotEmpty(one1)){
            return Result.error(Constants.CODE_400, "您已加入该班级,请勿重复加入!");
        }

        //加入班级
        JoinClass joinClass = new JoinClass();
        joinClass.setClassId(one.getId());
        joinClass.setUserId(userId);
        return Result.success(joinClassService.save(joinClass));
    }


    /**
     * 查询班级同学信息
     * @return
     */
    @GetMapping("/getStudentJoinClass")
    public Result getStudentJoinClass(@RequestParam Integer userId) {
        List<SysClass> studentJoinClass = joinClassService.getStudentJoinClass(userId);
        return Result.success(studentJoinClass);
    }

    /**
     * 发布成绩时学生下拉数据
     * @return
     */
    @GetMapping("/selectStudent")
    public Result selectStudent(@RequestParam Integer classId) {
        List<User> user = new ArrayList<>();
        List<JoinClass> list = joinClassService.list(Wrappers.<JoinClass>lambdaQuery().eq(JoinClass::getClassId, classId));
        if(ObjectUtils.isNotEmpty(list)){
            for (JoinClass joinClass : list) {
                User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getId, joinClass.getUserId()));
                user.add(one);
            }
        }
        return Result.success(user);
    }

}

